$(document).ready(function () {
   
    // 判断是否学生用户
    if (getCookie('login-usertype') == "student") {
        $('#dbpf').css('display', "none")
        $('#dbpy').css('display', "none")
        $('#dbpy1').css('display', "none")
        $('#navbox').html(`
            <span>
                <div class="btn-group">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></a>
                    <ul class="dropdown-menu" style="right:0;">
                        <li><a href="#" id="public-update">修改密码</a></li>
                        <li><a href="Personnel-list.html">答辩列表</a></li>
                        <li><a href="details.html">我的答辩</a></li>
                        <li><a href="#" id="askForDefence">申请答辩</a></li>
                        <li role="separator" class="divider" style="margin:0"></li>
                        <li><a href="#"  id="cancel">注销</a></li>
                    </ul>
                </div>
            </span>
            <span id="nav-position">同学</span>
            <span id="nav-username" style="color: blue;">` + getCookie('u-name') + `</span>
        `)
        // 显示答辩成绩
        $.ajax({
            type: 'GET',
            url: '/student/checkResult',
            xhrFields: {
                withCredentials: true
            },      
            success: function (data) {
                console.log(data)
                if (data.status == 0) {
                    $('#leftul').append(`<li><span style="font-weight: bold;">答辩成绩：</span><span class="public-userinfo" id="studbcj">`+data.result.record.grade+`分</span></li>`)
                } else {
                    $('#leftul').append(`<li><span style="font-weight: bold;">答辩成绩：</span><span class="public-userinfo">`+data.message+`</span></li>`)
                }
            }                 
        })
        $('#studbcj').after(`
        <p style="margin-top:63px">上传新论文或任务书时，会替换旧文件，请慎重使用！</p>
        <li>
            <form action="/" method="post" id="form-up">
                <button style="position:relative;padding:4px 28px;border:none;background:cornflowerblue;color:white;border-radius:4px">
                    <input id="form-up-input" name="paper" type="file" style="opacity:0;position:absolute;cursor:pointer;width:114px;height:28px;left:0;top:0">上传论文
                </button>
            </form>
            <form action="/" method="post" id="form-up1" style="margin-top:15px">
                <button style="position:relative;padding:4px 20px;border:none;background:cornflowerblue;color:white;border-radius:4px">
                    <input id="form-up1-input" name="charter" type="file" style="opacity:0;position:absolute;cursor:pointer;width:114px;height:28px;left:0;top:0">上传任务书
                </button>
            </form>
            </li>
        `)

      
         // 学生查看文件列表
        // var cid = 0
        $.ajax({
            type: 'GET',
            url: '/student/getFiles',
            xhrFields: {
                withCredentials: true
            },
            success: function (data) {
                console.log(data)
                if (data.status == 0) {
                    $('#details-top-select').html('')
                    var array = data.list
                    for (var i = 0; i < array.length; i++) {
                        $('#details-top-select').append(`
                            <option value='` + array[i].fid + `'>` + array[i].name + `</option>
                        `)
                    }
                    // cid = $('#details-top-select').find("option:selected").attr('value')
                } else {
                    $('#details-top-select').append(`
                            <option>论文、任务书列表获取失败</option>
                        `)
                }
            },
    })
    }
    // 学生上传论文
    $('#form-up-input').change(function (e) {
        var formData = new FormData($("#form-up")[0]);
        // formData.append("type", $("input[name='type']:checked").val())
        $.ajax({
            type: 'POST',
            url: '/student/uploadPaper',
            data: formData,
            xhrFields: {
                withCredentials: true
            },
        	dataType : 'json',
        	cache : false,
        	processData : false, // 不加会报错
        	contentType : false, // 不加会报错
        	beforeSend:function(){
        		$('#myModal-public3').modal({
                    backdrop: 'static',
                    keyboard: false
                })
                $('#myModal-public-body3').html("正在处理请求")
                $('#myModal-public3 .modal-footer').html('')
                $('#myModal-public3 .modal-header button').css('display','none')
        	},
            success: function (data) {
            	console.log(data)
                if (data.status == 0) {	     
            	     $('#myModal-public3 .modal-header button').css('display','block')
                    $('#myModal-public-body3').html('上传成功,刷新页面后生效！')
                    $('#myModal-public3 .modal-footer').html(
                        `   
                            <button type="button" class="btn" data-dismiss="modal" style="padding: 2px 20px;">关闭</button>    
                        `
                    )

                } else {
                      
                       $('#myModal-public3 .modal-header button').css('display','block')
                    $('#myModal-public3 .modal-footer').html(
                        `   
                            <button type="button" class="btn" data-dismiss="modal" style="padding: 2px 20px;">关闭</button>    
                        `
                    )
                    $('#myModal-public-body3').html(data.msg)
                }
            },

        })
    })
    // 学生上传任务书
    $('#form-up1-input').change(function (e) {
        var formData = new FormData($("#form1-up")[0]);
        // formData.append("type", $("input[name='type']:checked").val())
        $.ajax({
            type: 'POST',
            url: '/student/uploadCharter',
            data: formData,
            xhrFields: {
                withCredentials: true
            },
        	dataType : 'json',
        	cache : false,
        	processData : false, // 不加会报错
        	contentType : false, // 不加会报错
        	beforeSend:function(){
        		$('#myModal-public3').modal({
                    backdrop: 'static',
                    keyboard: false
                })
                $('#myModal-public-body3').html("正在处理请求")
                $('#myModal-public3 .modal-footer').html('')
                $('#myModal-public3 .modal-header button').css('display','none')
        	},
            success: function (data) {
            	console.log(data)
                if (data.status == 0) {	     
            	     $('#myModal-public3 .modal-header button').css('display','block')
                    $('#myModal-public-body3').html('上传成功,刷新页面后生效！')
                    $('#myModal-public3 .modal-footer').html(
                        `   
                            <button type="button" class="btn" data-dismiss="modal" style="padding: 2px 20px;">关闭</button>    
                        `
                    )

                } else {
                      
                       $('#myModal-public3 .modal-header button').css('display','block')
                    $('#myModal-public3 .modal-footer').html(
                        `   
                            <button type="button" class="btn" data-dismiss="modal" style="padding: 2px 20px;">关闭</button>    
                        `
                    )
                    $('#myModal-public-body3').html(data.msg)
                }
            },

        })
    })
    // ----------------------------------

    // 判断是否为老师
    if (getCookie('login-usertype') == "teacher") {
        $('#nav-username').html('' + getCookie('u-name') + '')
        $.ajax({
            type: 'POST',
            url: '/teacher/selectOneStudent',
            data: {
                "sid": getCookie('stuid'),
            },
            xhrFields: {
                withCredentials: true
            },
            success: function (data) {
                console.log(data)
                if (data.status == 0) {
                    setCookie('stu-rid',data.record.rid)
                }
            }

        })
    }

    // 判断是否书记员
    if (getCookie('login-usertype') == "clerk") {
        $('#dbpf').css('display', "none")
        $('#dbpy').css('display', "none")
        $('#dbpy1').css('display', "none")
        $('#public-body-div-right').css('display', "none")
        $('#public-body-div-right1').css('display', "block")
        $('#nav-position').html('书记员')
    }

    // 填写左边信息
    $('#detadils-stusno').html(getCookie('u-sno'))
    $('#detadils-stuname').html(getCookie('u-name'))
    $('#detadils-stuxy').html(getCookie('u-college'))
    $('#detadils-stuzy').html(getCookie('u-major'))
    $('#detadils-stuclass').html(getCookie('u-clazz'))


   

    // 评分
    var pfsj=0  //记录评分的变量
    $('#public-range').bind("mousemove click keyup", function () {
        pfsj=$(this).val()
        $('#range-count').html($(this).val())
        $('#public-range').css('background', '-webkit-linear-gradient(top, rgb(97, 189, 18), rgb(97, 189, 18)) 0% 0% / ' + $(this).val() + '% 100% no-repeat rgb(221, 221, 221)')
    })
    // 评语
    $('#dbcount').one("keyup", function () {
        $(this).after(`<div style="text-align: center;"><button class="publicbutton" id="details-submit">提交</button></div>`)
    })
    // 记录
    $('#editor').one("keyup", function () {
        $('#detadils-stuclass').after(`<div style="text-align: center;"><button class="publicbutton" style="margin-top:183px" id="details-submit-sjy">提交</button></div>`)
    })
    $('#public-body-div-left').on("mouseover", function () {
        // 评语评分提交
        $('#details-submit').off('click').click(function () {
            $.ajax({
                type: 'POST',
                url: '/teacher/updateScoreAndCommitByTeacher',
                data: {
                    "comment": $('#dbcount').html(),
                    "score": pfsj,
                    "tid": getCookie('teaid'),
                    "rid": getCookie('stu-rid')
                },
                xhrFields: {
                    withCredentials: true
                },
                beforeSend: function () {
                    $('#details-submit').attr({
                        disabled: "disabled"
                    });
                    $('#details-submit').html('正在处理请求...')
                },
                success: function (data) {
                    console.log(data)
                    if (data.status == 0) {
                        $('#myModal-public').modal({})
                        $('#myModal-public .modal-title').html('提交成功')
                        $('#myModal-public-body').html('答辩评语和答辩评分已成功提交！')
                    } else {
                        $('#myModal-public').modal({})
                        $('#myModal-public .modal-title').html('提交失败')
                        $('#myModal-public-body').html(data.message)
                    }
                },
                complete: function () {
                    $("#details-submit").removeAttr("disabled");
                    $('#details-submit').html('提交')
                }

            })
        })
        // 记录提交
        $('#details-submit-sjy').off('click').click(function () {
            $.ajax({
                type: 'POST',
                url: '/clerk/addContext',
                data: {
                    "context": editor.txt.html(),
                    "sid": getCookie('stuid')
                },
                xhrFields: {
                    withCredentials: true
                },
                beforeSend: function () {
                    $('#details-submit-sjy').attr({
                        disabled: "disabled"
                    });
                    $('#details-submit-sjy').html('正在处理请求...')
                },
                success: function (data) {
                    console.log(data)
                    if (data.status == 0) {
                        $('#myModal-public').modal({})
                        $('#myModal-public .modal-title').html('提交成功')
                        $('#myModal-public-body').html('答辩记录已成功提交！')
                    } else {
                        $('#myModal-public').modal({})
                        $('#myModal-public .modal-title').html('提交失败')
                        $('#myModal-public-body').html(data.message)
                    }
                },
                complete: function () {
                    $("#details-submit-sjy").removeAttr("disabled");
                    $('#details-submit-sjy').html('提交')
                }

            })
        })
    })

    //textarea高度自适应
    var autoTextarea = function (elem, extra, maxHeight) {
        extra = extra || 0;
        var isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window,
            isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera'),
            addEvent = function (type, callback) {
                elem.addEventListener ?
                    elem.addEventListener(type, callback, false) :
                    elem.attachEvent('on' + type, callback);
            },
            getStyle = elem.currentStyle ? function (name) {
                var val = elem.currentStyle[name];
                if (name === 'height' && val.search(/px/i) !== 1) {
                    var rect = elem.getBoundingClientRect();
                    return rect.bottom - rect.top -
                        parseFloat(getStyle('paddingTop')) -
                        parseFloat(getStyle('paddingBottom')) + 'px';
                };
                return val;
            } : function (name) {
                return getComputedStyle(elem, null)[name];
            },
            minHeight = parseFloat(getStyle('height'));
        elem.style.resize = 'none';
        var change = function () {
            var scrollTop, height,
                padding = 0,
                style = elem.style;
            if (elem._length === elem.value.length) return;
            elem._length = elem.value.length;
            if (!isFirefox && !isOpera) {
                padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'));
            };
            scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
            elem.style.height = minHeight + 'px';
            if (elem.scrollHeight > minHeight) {
                if (maxHeight && elem.scrollHeight > maxHeight) {
                    height = maxHeight - padding;
                    style.overflowY = 'auto';
                } else {
                    height = elem.scrollHeight - padding;
                    style.overflowY = 'hidden';
                };
                style.height = height + extra + 'px';
                scrollTop += parseInt(style.height) - elem.currHeight;
                document.body.scrollTop = scrollTop;
                document.documentElement.scrollTop = scrollTop;
                elem.currHeight = parseInt(style.height);
            };
        };
        addEvent('propertychange', change);
        addEvent('input', change);
        addEvent('focus', change);
        change();
    };
    var text = document.getElementById("dbcount");
    autoTextarea(text); // 调用
})